package com.heatup.apt.management.controller;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.heatup.apt.management.service.CoachPrivateSortService;
import com.heatup.apt.model.CoachPrivateSort;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.heatup.apt.common.constants.DataDictConstants;
import com.heatup.apt.common.util.JsonUtils;
import com.heatup.apt.management.service.DataDictService;
import com.heatup.apt.management.service.coach.CoachCourseFeeService;
import com.heatup.apt.management.service.coach.CoachService;
import com.heatup.apt.management.service.course.CourseService;
import com.heatup.apt.management.service.course.CourseStandardService;
import com.heatup.apt.management.service.store.StoreService;
import com.heatup.apt.management.util.ExcelDocumentor;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.course.CoachFeeDetailVo;
import com.heatup.apt.model.course.CoursePrivteFeeVO;

/**
 * Created by b3st9u on 16/8/22.
 */
@Controller
@RequestMapping("system/coach")
public class CoachController extends BaseController{
    @Resource
    private CoachService coachService;
    @Resource
    private StoreService storeService;
    @Resource
    private DataDictService dataDictService;
    @Resource
    private CourseStandardService courseStandardService;
    @Resource
    private CourseService courseService;
    @Resource
    private CoachCourseFeeService coachCourseFeeService;
    @Resource
    private CoachPrivateSortService coachPrivateSortService;
    
    private final static Logger logger = LoggerFactory.getLogger(CoachController.class);

    //解决日期自动转换 值传到后台 这样当前页面的数据就只能支持一种日期格式了
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));//spring 4.2 新方法
    }

    /**
     * 教练新增页面跳转
     * @return
     */
    @RequestMapping(value = "/to_coach_add")
    public ModelAndView toCoachAdd() {

        ModelAndView modelAndView = new ModelAndView("coach/coach-add");
        Map<String,Object> stature_man = dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_STATURE_MAN);
        modelAndView.addObject("stature_man", stature_man);//身材男
        modelAndView.addObject("stature_man_json", JsonUtils.obj2Json(stature_man));
        Map<String,Object> stature_women = dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_STATURE_WOMAN);
        modelAndView.addObject("stature_woman", stature_women);//身材女
        modelAndView.addObject("stature_woman_json", JsonUtils.obj2Json(stature_women));
        modelAndView.addObject("workTimes",dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_WORKING_TIME));//工作时长
        modelAndView.addObject("teachStyles",dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_TEACHING_STYLE));//授课风格
        modelAndView.addObject("courseStandards", JsonUtils.obj2Json(courseStandardService.queryAllCourseStandard()));//标准课程
        modelAndView.addObject("totalStudents",dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_PT_STUDENT_NUM));//累积私教学员
        modelAndView.addObject("stores",storeService.queryAllStore());

        // 主教练列表
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("status",1);
        paramMap.put("isChiefCoach",1);
        modelAndView.addObject("chiefCoachList",coachService.queryAllCoachInfoByCoachType(paramMap));

        return modelAndView;
    }


    /**
     * 教练编辑页面跳转
     * @return
     */
    @RequestMapping(value = "/to_coach_edit")
    public ModelAndView toCoachEdit(@RequestParam Integer id) {

        ModelAndView modelAndView = new ModelAndView("coach/coach-edit");
        Map<String,Object> stature_man = dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_STATURE_MAN);
        modelAndView.addObject("stature_man", stature_man);//身材男
        modelAndView.addObject("stature_man_json", JsonUtils.obj2Json(stature_man));
        Map<String,Object> stature_women = dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_STATURE_WOMAN);
        modelAndView.addObject("stature_woman", stature_women);//身材女
        modelAndView.addObject("stature_woman_json", JsonUtils.obj2Json(stature_women));
        modelAndView.addObject("workTimes",dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_WORKING_TIME));//工作时长
        modelAndView.addObject("teachStyles",dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_TEACHING_STYLE));//授课风格
        modelAndView.addObject("courseStandards", JsonUtils.obj2Json(courseStandardService.queryAllCourseStandard()));//标准课程
        modelAndView.addObject("totalStudents",dataDictService.queryDictMap(DataDictConstants.DICT_TYPE_PT_STUDENT_NUM));//累积私教学员
        modelAndView.addObject("stores",storeService.queryAllStore());
        modelAndView.addObject("coach",coachService.queryCoachById(id));

        // 主教练列表
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("status",1);
        paramMap.put("isChiefCoach",1);
        modelAndView.addObject("chiefCoachList",coachService.queryAllCoachInfoByCoachType(paramMap));


        return modelAndView;
    }

    /**
     * 教练离职
     * @return
     */
    @RequestMapping(value = "/coach_offline")
    @ResponseBody
    public String coachOffline(@RequestParam Integer id) {
        String result = "";
        if (id == null) {
            result = "离职失败";
            return result;
        }
        boolean success = coachService.offlineCoachById(id);
        if (success) {
            result = "离职成功";
        }

        return result;
    }

    /**
     * 教练删除
     * @return
     */
    @RequestMapping(value = "/coach_delete")
    @ResponseBody
    public String coachDelete(@RequestParam Integer id) {
        String result = "";
        if (id == null) {
            result = "删除失败";
            return result;
        }
        boolean success = coachService.delCoachById(id);
        if (success) {
            result = "删除成功";
        }

        return result;
    }

    /**
     * 教练移除轮排
     *
     * @param coachId 教练 ID
     * @return true 操作成功 / false 操作失败
     */
    @RequestMapping(value = "/coach_remove_sort")
    @ResponseBody
    public String coachRemoveSort(@RequestParam Integer coachId) {
        String result = "";
        if (coachId == null) {
            result = "ID 不能为空 操作失败!";
            return result;
        }
        CoachInfo coachInfo = new CoachInfo();
        coachInfo.setId(coachId);
        coachInfo.setIsPrivateCoachSort(2);//不轮排
        boolean s = coachService.updateSelectiveById(coachInfo);
        if (!s) {
            logger.error("教练更新移除轮排状态失败");
        }
        CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
        coachPrivateSort.setCoachId(coachId);
        boolean success = coachPrivateSortService.deleteSelective(coachPrivateSort);
        if (success) {
            result = "移除成功!";
        }

        return result;
    }

    /**
     * 教练保存
     * @return
     */
    @RequestMapping(value = "/coach_save")
    @ResponseBody
    public String coachSave(CoachInfo coachInfo){
        if (coachInfo == null) {
            return "false";
        }
        try{
            if (coachService.saveCoach(coachInfo)) {
                return "success";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "false";
    }

    /**
     * 教练列表跳转
     * @return 教练列表视图
     */
    @RequestMapping(value = "/to_coach_list")
    public ModelAndView coachList(){
        ModelAndView modelAndView = new ModelAndView("coach/coach-list");
        modelAndView.addObject("stores",storeService.queryAllStore());
        return modelAndView;
    }


    /**
     * 教练私教列表跳转
     * @return 教练私教列表视图
     */
    @RequestMapping(value = "/to_coach_private_list")
    public ModelAndView coachPrivateList(){
        ModelAndView modelAndView = new ModelAndView("coach/coach-private-list");
        modelAndView.addObject("stores",storeService.queryAllStore());
        return modelAndView;
    }

    /**
     * 私教教练排序
     *
     * @author blank 2017/8/3 下午4:46
     */
    @RequestMapping("sort")
    public void sort(HttpServletResponse response, String sortString){

        try {

            Integer count = coachService.updateSort(sortString);
            responseSendMsg(response, count + "");
        } catch (Exception e) {
            e.printStackTrace();
            responseSendMsg(response, "排序失败!");
        }
    }

    /**
     * 教练列表分页查询
     * @param response
     * @return
     */
    @RequestMapping(value = "/coach_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void coachList(HttpServletResponse response,
                             @RequestParam int pageIndex,
                             @RequestParam int pageSize,
                             Integer id,
                             String nickName,
                             String mobile,
                             Integer storeId,
                             Integer workType,
                             Integer status,
                             Integer type
                          ) {

        if (pageIndex > 0)
            --pageIndex;
        if (pageSize <=0)
            pageSize = 10;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("id", id);
        paramsMap.put("nickName", nickName);
        paramsMap.put("mobile", mobile);
        paramsMap.put("storeId", storeId);
        paramsMap.put("workType", workType);
        paramsMap.put("status", status);
        paramsMap.put("type", type);

        Map<String, Object> map = coachService.queryCoachPageList(paramsMap);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("coachList", map.get("coachList"));
        jsonObject.put("coachCount", map.get("coachCount"));
        responseSendMsg(response, JsonUtils.toJsonStrWithDateFormat(jsonObject));
    }

    /**
     * 教练私教列表跳转
     * @return 教练私教列表视图
     */
    @RequestMapping(value = "/to_coach_private_sort_list")
    public ModelAndView coachPrivateSortList(){
        ModelAndView modelAndView = new ModelAndView("coach/coach-private-sort-list");
        modelAndView.addObject("stores",storeService.queryAllStore());
        return modelAndView;
    }

    /**
     * 教练轮排
     * @param response
     * @return
     */
    @RequestMapping(value = "/coach_private_sort_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void coachPrivateSortList(HttpServletResponse response, Integer id,
                          String nickName, String mobile) {

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", id);
        paramsMap.put("nickName", nickName);
        paramsMap.put("mobile", mobile);

        Map<String, Object> map = coachService.queryCoachPrivateSortList(paramsMap);
        responseSendMsg(response, JsonUtils.toJsonStrWithDateFormat(map));
    }



    /**
     * 教练课时费列表跳转
     * @return
     */
    @RequestMapping(value = "/class_fee_details")
    public ModelAndView feeDetails(String id,String year, String month){
        ModelAndView modelAndView = new ModelAndView("coach/class_fee_details");
        modelAndView.addObject("coachId", id);
        modelAndView.addObject("stores",storeService.queryAllStore());
        modelAndView.addObject("yearMonth",year + "-" + month);
        return modelAndView;
    }

    /**
     * 教练团课费用统计
     *
     * @author blank 2017/9/8 上午9:40
     */
    @RequestMapping(value = "/fee_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void feeList(HttpServletResponse response,
                             @RequestParam String yearMonth,
                             @RequestParam Integer storeId,
                             @RequestParam Integer coachId,
                             @RequestParam Integer courseId) {

    	Map<String, Object> paramsMap = new HashMap<>();

        paramsMap.put("coachId", coachId);
        paramsMap.put("storeId", storeId == 0 ? null : storeId);
        paramsMap.put("yearMonth", StringUtils.isBlank(yearMonth) ? null: yearMonth);
        paramsMap.put("courseId", courseId);
        List<CoachFeeDetailVo> list = courseService.queryCoachFeeDetail(paramsMap);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("feeList", list);
        jsonObject.put("feeListCount", list.size());
        responseSendMsg(response, jsonObject.toString());
    }
    
    /**
     * 私教费用统计明细
     * @param response
     * @param yearMonth
     * @param storeId
     * @param coachId
     * @param orderId
     */
    @RequestMapping(value = "/private_fee_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void privateFeeList(HttpServletResponse response,
                             @RequestParam String yearMonth,
                             @RequestParam Integer storeId,
                             @RequestParam Integer coachId,
                             @RequestParam Integer orderId) {
    	Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("coachId", coachId);
        paramsMap.put("storeId", storeId == 0 ? null : storeId);
        paramsMap.put("yearMonth", StringUtils.isBlank(yearMonth) ? null: yearMonth);
        paramsMap.put("orderId", orderId);
        List<CoursePrivteFeeVO> list = coachCourseFeeService.queryCoachPrivateFeeDetail(paramsMap);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("priFeeList", list);
        jsonObject.put("priFeeListCount", list.size());
        responseSendMsg(response, jsonObject.toString());
    }
    
    /**
     * 檬营费用统计明细
     * @param response
     * @param yearMonth
     * @param storeId
     * @param coachId
     * @param courseId
     */
    @RequestMapping(value = "/camp_fee_list", method = {RequestMethod.GET, RequestMethod.POST})
    public void campFeeList(HttpServletResponse response,
                             @RequestParam String yearMonth,
                             @RequestParam Integer storeId,
                             @RequestParam Integer coachId,
                             @RequestParam Integer courseId) {
    	Map<String, Object> paramsMap = new HashMap<>();

        paramsMap.put("coachId", coachId);
        paramsMap.put("storeId", storeId == 0 ? null : storeId);
        paramsMap.put("yearMonth", StringUtils.isBlank(yearMonth) ? null: yearMonth);
        paramsMap.put("courseId", courseId);
        Map<String, Object> map = coachCourseFeeService.queryCoachCampFeeDetail(paramsMap);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("campFeeList", map.get("campList"));
        jsonObject.put("campFeeListCount", map.get("campCount"));
        responseSendMsg(response, jsonObject.toString());
    }
    
    
//    @ResponseBody
//    @RequestMapping("/download_detail")
//    public String to_download_detail(HttpServletRequest request,HttpServletResponse response){
//    	Integer cashcardId = RequestTools.RequestInt(request, "cashcardId",0);
//    	Map<String, Object> responseMap = new HashMap<>();
//    	responseMap = cashcardService.downloadDetail(cashcardId);
//    	JSONObject jsonObject = new JSONObject();
//		Map<String, Object> map = new HashMap<>();
//		jsonObject.put("data", responseMap);
//		return jsonObject.toJSONString();
//    }
	/**
	 * 团课收益明细下载
	 *
	 * @return
	 */
    @ResponseBody
    @RequestMapping("/download_fee_detail")
	public String downloadCashcardDetail(@RequestParam String yearMonth,
            @RequestParam Integer storeId,
            @RequestParam Integer coachId,
            @RequestParam Integer courseId,
            @RequestParam int type) {
		String downloadPath = ManageConfigPropertiesUtil.getString("uploadImagDir");
		String fileName = "coaFeeDetail" + System.currentTimeMillis() + ".xls";
		
		//创建目录
		File dirFile = new File(downloadPath);
		if (dirFile.exists()) {
			if (!dirFile.isDirectory()) {
				dirFile.mkdir();
			}
		} else {
			dirFile.mkdir();
		}
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("coachId", coachId);
        paramsMap.put("storeId", storeId == 0 ? null : storeId);
        paramsMap.put("yearMonth", StringUtils.isBlank(yearMonth) ? null: yearMonth);
        paramsMap.put("courseId", courseId);
        
		Map<String, String> columns = null;
		if(type == 1) {//团课
			columns = this.getTeamColumsTitle();
		    List<CoachFeeDetailVo>  list = courseService.queryCoachFeeDetail(paramsMap);
		    ExcelDocumentor documentor = new ExcelDocumentor();
			documentor.exportTable(list, columns, new File(downloadPath+File.separator+fileName));
		} else if(type == 3) {//训练营
			columns = this.getCampColumsTitle();
			Map<String, Object> map = coachCourseFeeService.queryCoachCampFeeDetail(paramsMap);
			@SuppressWarnings("unchecked")
			List<CoursePrivteFeeVO> list = (List<CoursePrivteFeeVO>) map.get("campList");
			ExcelDocumentor documentor = new ExcelDocumentor();
			documentor.exportTable(list, columns, new File(downloadPath+File.separator+fileName));
		} else if(type == 2) {// 私教
			columns = this.getPriColumsTitle();
			List<CoursePrivteFeeVO> list  = coachCourseFeeService.queryCoachPrivateFeeDetail(paramsMap);
			ExcelDocumentor documentor = new ExcelDocumentor();
			documentor.exportTable(list, columns, new File(downloadPath+File.separator+fileName));
		}
		
		Map<String, Object> map = new HashMap<>();
		map.put("fileName",fileName);
		map.put("result", "success");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", map);
		return jsonObject.toJSONString();
	}
	
	
	
	//团课
	public Map<String, String> getTeamColumsTitle(){
		Map<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("startTime","上课时间");
		columns.put("serviceName","课程名称");
		columns.put("courseId","课程ID");
		columns.put("price","会员价");
		columns.put("primePrice","原价");
		columns.put("storeName","门店");
		columns.put("maxCount","上限");
		columns.put("currentCount","已报");
		columns.put("waitCount","排队");
		columns.put("blankCourse","白板");
		columns.put("nomalCourse","课时费");
		columns.put("hotCourse","爆场");
		columns.put("subTotal","小计");
		return columns;
	}
	
	//训练营
	public Map<String, String> getCampColumsTitle(){
		Map<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("courseSigninStartTime","开始时间");
		columns.put("courseSigninEndTime","结束时间");
		columns.put("serviceName","课程名称");
		columns.put("courseId","课程ID");
		columns.put("price","会员价");
		columns.put("primePrice","原价");
		columns.put("course_order_amt","课程总实收");
		columns.put("storeName","门店");
		columns.put("courseNumber","课时");
		columns.put("maxCount","上限");
		columns.put("currentCount","已报");
		columns.put("waitCount","排队");
		columns.put("planA","方案A");
		columns.put("palnB","方案B");
		return columns;
	}
	//私教
	public Map<String, String> getPriColumsTitle(){
		Map<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("closeTime","销课时间");
		columns.put("serviceName","课程名称");
		columns.put("orderId","订单ID");
		columns.put("storeName","销课门店");
		columns.put("courseNumber","课时");
		columns.put("courseCount","总课时");
		columns.put("nickName","用户");
		columns.put("mobile","手机");
		columns.put("amount","订单总额");
		columns.put("per_course_amt","课时单价");
		columns.put("priCourseRate","分成比例(%)");
		columns.put("real_amt","课时费");
		return columns;
	}
}
